package org.xx.armory.spring5.jdbc;

import java.util.HashMap;
import java.util.Map;

import static java.sql.Types.ARRAY;
import static java.sql.Types.BIGINT;
import static java.sql.Types.BINARY;
import static java.sql.Types.BIT;
import static java.sql.Types.BLOB;
import static java.sql.Types.BOOLEAN;
import static java.sql.Types.CHAR;
import static java.sql.Types.CLOB;
import static java.sql.Types.DATE;
import static java.sql.Types.DECIMAL;
import static java.sql.Types.DOUBLE;
import static java.sql.Types.FLOAT;
import static java.sql.Types.INTEGER;
import static java.sql.Types.LONGNVARCHAR;
import static java.sql.Types.LONGVARBINARY;
import static java.sql.Types.LONGVARCHAR;
import static java.sql.Types.NCHAR;
import static java.sql.Types.NUMERIC;
import static java.sql.Types.NVARCHAR;
import static java.sql.Types.REAL;
import static java.sql.Types.REF_CURSOR;
import static java.sql.Types.SMALLINT;
import static java.sql.Types.TIME;
import static java.sql.Types.TIMESTAMP;
import static java.sql.Types.TINYINT;
import static java.sql.Types.VARBINARY;
import static java.sql.Types.VARCHAR;
import static org.springframework.jdbc.core.SqlTypeValue.TYPE_UNKNOWN;

/**
 * SqlType 相关的工具类。
 */
public final class SqlTypeUtils {
    private static final Map<Integer, String> SQL_TYPE_NAMES = createSqlTypeNames();

    private static Map<Integer, String> createSqlTypeNames() {
        final var result = new HashMap<Integer, String>();

        result.put(0, "");
        result.put(TYPE_UNKNOWN, "UNKNOWN");
        result.put(ARRAY, "ARRAY");
        result.put(BIGINT, "BIGINT");
        result.put(BINARY, "BINARY");
        result.put(BIT, "BIT");
        result.put(BLOB, "BLOB");
        result.put(BOOLEAN, "BOOLEAN");
        result.put(CHAR, "CHAR");
        result.put(CLOB, "CLOB");
        result.put(DATE, "DATE");
        result.put(DECIMAL, "DECIMAL");
        result.put(DOUBLE, "DOUBLE");
        result.put(FLOAT, "FLOAT");
        result.put(INTEGER, "INTEGER");
        result.put(LONGNVARCHAR, "LONGNVARCHAR");
        result.put(LONGVARBINARY, "LONGVARBINARY");
        result.put(LONGVARCHAR, "LONGVARCHAR");
        result.put(NCHAR, "NCHAR");
        result.put(NUMERIC, "NUMERIC");
        result.put(NVARCHAR, "NVARCHAR");
        result.put(REAL, "REAL");
        result.put(SMALLINT, "SMALLINT");
        result.put(TIME, "TIME");
        result.put(TIMESTAMP, "TIMESTAMP");
        result.put(TINYINT, "TINYINT");
        result.put(VARBINARY, "VARBINARY");
        result.put(VARCHAR, "VARCHAR");
        result.put(REF_CURSOR, "REF_CURSOR");

        return result;
    }

    /**
     * 根据SqlType类型，获取对应的名字。
     *
     * @param sqlType
     *         SqlType类型。
     * @return 对应的名字，如果找不到则返回 {@literal unknown-sql-type(sqlType)}
     * @see java.sql.Types
     */
    public static String sqlTypeName(
            int sqlType
    ) {
        return SQL_TYPE_NAMES.getOrDefault(sqlType, "(" + sqlType + ")");
    }
}
